<?php

namespace plugin\ycMassage\app\shop\controller;

use app\common\builder\FormBuilder;
use app\common\service\UploadService;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageMchBill;
use plugin\ycMassage\app\model\MassageShopBill;
use plugin\ycMassage\app\model\MassageUserAgentBill;
use plugin\ycMassage\app\model\MassageUserFinanceAccount;
use plugin\ycMassage\app\model\MassageUserTechnicianBill;
use plugin\ycMassage\app\model\MassageUserWallet;
use plugin\ycMassage\app\model\MassageWithdrawal;
use plugin\ycMassage\utils\enum\ActionIdentity;
use plugin\ycMassage\utils\enum\Examine;
use support\Request;
use think\Exception;
use think\facade\Db;

class WalletController extends BaseController
{
    public function withdrawal(Request $request)
    {
        $UserWallet = MassageUserWallet::where(['uid' => $request->uid])->find();
        if (!$UserWallet) {
            return $this->fail('数据不存在');
        }
        if ($request->method() === 'POST') {
            $D = $request->post();
            $channels = $request->post('channels');
            if (!$channels) {
                return $this->fail('请选择收款账户');
            }
            $money = $request->post('money', 0);
            if (!$money) {
                return $this->fail('请输入提现金额');
            }
            if ($request->use_mch_id) {
                return $this->mchWithdrawal($request);
            } else {
                return $this->shopWithdrawal($request);
            }
        }
        $builder = new FormBuilder;
        $builder->setMethod('POST');
        if ($request->use_mch_id) {
            $builder->addComponent('mch_money', 'info', '可提现余额', '', [
                'col'           => 8,
            ]);
            $builder->addComponent('mch_freeze_money', 'info', '冻结中', '', [
                'col'           => 8,
            ]);
            $builder->addComponent('mch_money_sum', 'info', '累计收益', '', [
                'col'           => 8,
            ]);
        } else {
            $builder->addComponent('shop_money', 'info', '可提现余额', '', [
                'col'           => 8,
            ]);
            $builder->addComponent('shop_freeze_money', 'info', '冻结中', '', [
                'col'           => 8,
            ]);
            $builder->addComponent('shop_money_sum', 'info', '累计收益', '', [
                'col'           => 8,
            ]);
        }
        $builder->addDivider('提现');
        $FinanceAccount = MassageUserFinanceAccount::where(['uid' => $request->uid])->select();
        $channels = [];
        foreach ($FinanceAccount as $key => $value) {
            $name = '';
            switch ($value->channels) {
                case 'alipay_payment_code':
                    $name = '支付宝收款码';
                    break;
                case 'wechat_payment_code':
                    $name = '微信收款码';
                    break;
                case 'bank_transfer':
                    $name = '银行卡';
                    break;
            }
            $channels[] = [
                'value' => $value->channels,
                'label' => $name . '(' . $value->name . ')'
            ];
        }
        $builder->addRow('channels', 'select', '收款账户', '', [
            'col' => 12,
            'props' => [
                'placeholder' => '请选择收款账户'
            ],
            'prompt' => [
                'text' => "收款账户请打开移动端，在个人中心-设置-账户安全-收款账户中绑定",
            ],
            'options' => $channels
        ]);
        $builder->addRow('money', 'number', '提现金额', null, [
            'col' => 12,
            'props' => [
                'placeholder' => '请输入提现金额',
                'min' => 0,
                'max' => $request->use_mch_id ? $UserWallet->mch_money : $UserWallet->shop_money,
                'controls' => false,
                'precision' => 2
            ]
        ]);
        $data = $builder->setData($UserWallet)->create();
        return $this->successRes($data);
    }
    public function mchWithdrawal(Request $request)
    {
        $uid = $request->uid;
        $saas_appid = $request->saas_appid;
        $channels = $request->post('channels');
        $money = (float)$request->post('money', 0);
        $action = ActionIdentity::MCH['value'];
        $withdrawal = getHpConfig('', $saas_appid, 'withdrawal');
        $mch_withdrawal_fee = 0;
        $mch_min_withdrawal_money = 0;
        if (isset($withdrawal['mch_withdrawal_fee'])) {
            $mch_withdrawal_fee = (int)$withdrawal['mch_withdrawal_fee'];
        }
        if (isset($withdrawal['mch_min_withdrawal_money'])) {
            $mch_min_withdrawal_money = (float)$withdrawal['mch_min_withdrawal_money'];
        }
        if ($mch_min_withdrawal_money > 0 && $money < $mch_min_withdrawal_money) {
            return $this->fail('提现金额不能小于' . $mch_min_withdrawal_money);
        }
        Db::startTrans();
        try {
            $MassageUserFinanceAccount = MassageUserFinanceAccount::where(['uid' => $uid, 'channels' => $channels])->find();
            if (!$MassageUserFinanceAccount) {
                throw new Exception('请先绑定提现账号');
            }
            $price_fee = 0;
            if ($mch_withdrawal_fee > 0) {
                $price_fee = $money * $mch_withdrawal_fee / 100;
            }
            $price = $money - $price_fee;
            $MassageUserWallet = MassageUserWallet::where(['uid' => $uid])->find();
            if (!$MassageUserWallet) {
                throw new Exception('用户未开通钱包');
            }
            if($MassageUserWallet->mch_money>$money + $price_fee){
                $price = $money + $price_fee;
            }else{
                if($MassageUserWallet->mch_money>$money){
                    $price=$MassageUserWallet->mch_money;
                    $money=$price-$price_fee;
                }else{
                    $price=$money;
                    $money=$money-$price_fee;
                }
            }
            $MassageWithdrawal = new MassageWithdrawal();
            $MassageWithdrawal->uid = $uid;
            $MassageWithdrawal->saas_appid = $saas_appid;
            $MassageWithdrawal->channels = $channels;
            $MassageWithdrawal->name = $MassageUserFinanceAccount->name;
            $MassageWithdrawal->mobile = $MassageUserFinanceAccount->mobile;
            $MassageWithdrawal->openid = $MassageUserFinanceAccount->openid;
            $MassageWithdrawal->mp_openid = $MassageUserFinanceAccount->mp_openid;
            $MassageWithdrawal->account = $MassageUserFinanceAccount->account;
            $MassageWithdrawal->bank = $MassageUserFinanceAccount->bank;
            if ($MassageUserFinanceAccount->qrcode) {
                $MassageWithdrawal->qrcode = UploadService::path($MassageUserFinanceAccount->qrcode);
            }
            $MassageWithdrawal->money = $money;
            $MassageWithdrawal->old_withdrawal_price = $MassageUserWallet->mch_money;
            $MassageWithdrawal->new_withdrawal_price = $MassageUserWallet->mch_money - $price;
            $MassageWithdrawal->state = Examine::WAIT['value'];
            $MassageWithdrawal->price_fee = $price_fee;
            $MassageWithdrawal->withdrawal_fee = $mch_withdrawal_fee;
            $MassageWithdrawal->action = $action;
            $MassageWithdrawal->save();
            MassageMchBill::decrease('提现', $uid, $price);
            Db::commit();
            return $this->success('提现成功');
        } catch (\Throwable $th) {
            Db::rollback();
            return $this->fail($th->getMessage());
        }
    }
    public function shopWithdrawal(Request $request)
    {
        $uid = $request->uid;
        $saas_appid = $request->saas_appid;
        $channels = $request->post('channels');
        $money = (float)$request->post('money', 0);
        $action = ActionIdentity::STORE['value'];
        $withdrawal = getHpConfig('', $saas_appid, 'withdrawal');
        $mch_withdrawal_fee = 0;
        $mch_min_withdrawal_money = 0;
        if (isset($withdrawal['mch_withdrawal_fee'])) {
            $mch_withdrawal_fee = (int)$withdrawal['mch_withdrawal_fee'];
        }
        if (isset($withdrawal['mch_min_withdrawal_money'])) {
            $mch_min_withdrawal_money = (float)$withdrawal['mch_min_withdrawal_money'];
        }
        if ($mch_min_withdrawal_money > 0 && $money < $mch_min_withdrawal_money) {
            return $this->fail('提现金额不能小于' . $mch_min_withdrawal_money);
        }
        Db::startTrans();
        try {
            $MassageUserFinanceAccount = MassageUserFinanceAccount::where(['uid' => $uid, 'channels' => $channels])->find();
            if (!$MassageUserFinanceAccount) {
                throw new Exception('请先绑定提现账号');
            }
            $price_fee = 0;
            if ($mch_withdrawal_fee > 0) {
                $price_fee = $money * $mch_withdrawal_fee / 100;
            }
            $price = $money - $price_fee;
            $MassageUserWallet = MassageUserWallet::where(['uid' => $uid])->find();
            if (!$MassageUserWallet) {
                throw new Exception('用户未开通钱包');
            }
            if($MassageUserWallet->shop_money>$money + $price_fee){
                $price = $money + $price_fee;
            }else{
                if($MassageUserWallet->shop_money>$money){
                    $price=$MassageUserWallet->shop_money;
                    $money=$price-$price_fee;
                }else{
                    $price=$money;
                    $money=$money-$price_fee;
                }
            }
            $MassageWithdrawal = new MassageWithdrawal();
            $MassageWithdrawal->uid = $uid;
            $MassageWithdrawal->saas_appid = $saas_appid;
            $MassageWithdrawal->channels = $channels;
            $MassageWithdrawal->name = $MassageUserFinanceAccount->name;
            $MassageWithdrawal->mobile = $MassageUserFinanceAccount->mobile;
            $MassageWithdrawal->openid = $MassageUserFinanceAccount->openid;
            $MassageWithdrawal->mp_openid = $MassageUserFinanceAccount->mp_openid;
            $MassageWithdrawal->account = $MassageUserFinanceAccount->account;
            $MassageWithdrawal->bank = $MassageUserFinanceAccount->bank;
            if ($MassageUserFinanceAccount->qrcode) {
                $MassageWithdrawal->qrcode = UploadService::path($MassageUserFinanceAccount->qrcode);
            }
            $MassageWithdrawal->money = $money;
            $MassageWithdrawal->old_withdrawal_price = $MassageUserWallet->shop_money;
            $MassageWithdrawal->new_withdrawal_price = $MassageUserWallet->shop_money - $price;
            $MassageWithdrawal->state = Examine::WAIT['value'];
            $MassageWithdrawal->price_fee = $price_fee;
            $MassageWithdrawal->withdrawal_fee = $mch_withdrawal_fee;
            $MassageWithdrawal->action = $action;
            $MassageWithdrawal->save();
            MassageShopBill::decrease('提现', $uid, $price);
            Db::commit();
            return $this->success('提现成功');
        } catch (\Throwable $th) {
            Db::rollback();
            return $this->fail($th->getMessage());
        }
    }
}
